package com.smilive.springcloud.controller;

import com.smilive.springcloud.entity.CommonResult;
import com.smilive.springcloud.entity.Payment;
import com.smilive.springcloud.service.IPaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-07-06
 */
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Autowired
    private IPaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;


    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment){
        boolean save = paymentService.save(payment);
        log.info("插入结果:{}",save);
        if (save){
            return new CommonResult(200,"查询成功+serverPort:"+serverPort);
        }else {
            return new CommonResult(444,"创建失败");
        }
    }

    @GetMapping("/get/{id}")
    public CommonResult get(@PathVariable("id")long id){
        Payment payment = paymentService.getById(id);
        log.info("查询结果:{}",payment);
        if (payment != null){
            return new CommonResult(200,"查询成功+serverPort:"+serverPort,payment);
        }else {
            return new CommonResult(444,"查询失败ID"+id);
        }
    }

    @GetMapping(value = "/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();

        for (String service : services) {
            log.info("*****element:" + service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId()+"\t" + instance.getHost() +
                    "\t" + instance.getPort() +"\t" + instance.getUri());
        }

        return  this.discoveryClient;
    }


}

